from datetime import datetime
from termcolor import colored
import os
import re
import subprocess
import operation
import time
import xml.etree.ElementTree as ET
from Config import adb
# ------
import json
from operation import *
import requests#type:ignore
from fuzzywuzzy import fuzz#type:ignore
# --------------------------------XML--LEVEL1----------------------------------------
 

# -------------------------------XML---LEVEL2-------------------------------------
class GUIAnalyze():
    def __init__(self):
        self.xmlpath=xmlshot()
        self.findwidgets=traverse(self.xmlpath)
def clickwidgets(GUI0,tomatch,conditionfun=lambda item,i,con,cl,pro,loc: item in con.lower(),fmtstr='{con}',CLICK=True,BREAK=True):
    if GUI0=='':
        GUI0=GUIAnalyze()
        print(GUI0.findwidgets)
    searchlist=[]
    if not (type(tomatch) is list):
        tomatch=[tomatch]
    if type(GUI0) is list:
        widgetslist=GUI0
    else:
        widgetslist=GUI0.findwidgets
    for wlitem in widgetslist:
        i,con,cl,pro,loc = wlitem
        Continue=True
        for item in tomatch:
            if conditionfun(item,i,con,cl,pro,loc):
                searchlist.append(wlitem)
                if CLICK:
                    operation.click(loc[0],loc[1])
                    print(colored(f'clickwidgets({tomatch}):clicked {con}','magenta'))
                    if BREAK:
                        Continue=False
                        break
        if not Continue:
            break
    fmtlist = []
    for slitem in searchlist:
        i, con, cl, pro, loc = slitem 
        fmtitem = fmtstr.format(i=i, con=con, cl=cl, pro=pro, loc=loc)
        fmtlist.append(fmtitem)
    if not fmtlist:
        print(colored(f'clickwidgets({tomatch}):fail','red'))
    return fmtlist
# -------------------------------XML----LEVEL3------------------------------------------
def ads_agreements():
    GUI0=GUIAnalyze()
    clickwidgets(GUI0,['跳过','skip'])
    clickwidgets(GUI0,['同意'])
    if clickwidgets(GUI0,['协议','agreement'],CLICK=False):
        clickwidgets(GUI0,['checkable'],conditionfun=lambda item,i,con,cl,pro,loc:item in str(pro).lower())
        return True
    return False
# def clickEnter():
#     words_locs=ocrall()
#     for item in words_locs:
#         if ('搜索' in item[0])or ('开始' in item[0]) and (item[1]>1100 )and(item[2]>2600):
#             operation.click(1200,2700)
#             return True
#     return clickwidgets('',['发送','send','拨号'])
# ------------------------------XML------LEVEL4--------------
# def typeAndEnter(text,GUI0=''):
#     if GUI0=='':
#         GUI0=GUIAnalyze()
#     typebar=False
#     print(GUI0.findwidgets)
#     for item in GUI0.findwidgets: 
#         i,con,cl,pro,loc = item
#         if (( '搜索框' or '搜索栏')in con) and 'clickable' in str(pro):
#             operation.click(loc[0],loc[1])
#             typebar=True
#             time.sleep(1)
#             operation.text(text)
#             operation.click(loc[0],loc[1])
#             break
#         elif '搜索' in con:
#             print(pro)
#             operation.click(loc[0],loc[1])
#             operation.click(loc[0]/2,loc[1])
#             typebar=True
#             time.sleep(1)
#             operation.text(text)
#             operation.click(loc[0]/2,loc[1])
#             break
#         elif 'edittext' in cl.lower():
#             operation.click(loc[0],loc[1])
#             typebar=True
#             time.sleep(1)
#             operation.text(text)
#             operation.click(loc[0],loc[1])
#             break
#         elif '拨号' in con:
#             operation.text(text)
#             break
#     if typebar==False:
#         print(colored('No type bar','magenta'))
#     print(text)
#     if clickwidgets('',text,CLICK=False):
#         if clickEnter():
#             print(colored(f'typeAndEnter({text}):True','magenta'))
#             return True
#     else:
#         print(colored(f'typeAndEnter({text}):False','magenta'))
#         return False
def scrollfind(findnamelist,option='vert'):
    global rtn
    ads_agreements()
    Continue=True  
    rtn=False
    if type(findnamelist) is str:
        findnamelist=[findnamelist]
    if option=='hori':
        for i in range(7):
            operation.swipe(100,1400,'left','short','vfast')
    elif option=='vert':
        for i in range(5):
            operation.swipe(640,1000,'down','short','vfast')   
    cnt=0
    oldGUI0list=[]
    while cnt<12 and Continue:
        cnt=cnt+1
        if cnt==1:
            oldGUI0list=[]
        else:
            oldGUI0list=GUI0.findwidgets
        GUI0=GUIAnalyze()
        GUI0list=GUI0.findwidgets
        if clickwidgets(GUI0,findnamelist): 
            rtn=True   
            Continue=False
        if( not Continue ):
            Continue=False
        if oldGUI0list==GUI0list: 
            Continue=False
            rtn=False
        if Continue:
            if option=='vert':
                operation.swipe(640,1400,'up','short','fast')
            elif option=='hori':
                operation.swipe(640,1400,'right','short','vfast')
    print(colored(f'scrollfind({findnamelist}):{rtn}','cyan'))
    return rtn

def switchto(app):
    operation.keycode(3)
    rtn=scrollfind(app,'hori')
    return rtn
def scrollall(rev=False): 
    infolist=[]
    rawlist=[]
    cnt=0
    if not rev:
        down=['down','up']
    else:
        down=['up','down']
    for i in range(5):
        operation.swipe(640,1000,down[0],'short','vfast')  
    while cnt<15:
        cnt=cnt+1
        GUI0=GUIAnalyze()
        oldrawlist=rawlist
        rawlist=formatlist(GUI0.findwidgets,'{con}')
        for rlitem in rawlist:
            if not rlitem in infolist:
                if (not 'MB' in rlitem) and(not 'KB' in rlitem) and (not 'GB' in rlitem) and (not ''==rlitem):
                    infolist.append(rlitem)
        if  oldrawlist==rawlist:
            print(colored(f'scrollall():{infolist}','cyan'))
            return infolist
        else:
            operation.swipe(640,2300,down[1],'mid','normal')
    return infolist
